
const runtimeConfig = useRuntimeConfig();
const { apiBaseUrl } = runtimeConfig.public;


function useGetFetchOptions(options = {}){
  options.baseURL = apiBaseUrl;
  options.baseURL = options.baseURL ?? fetchConfig.baseURL
  options.headers = options.headers ?? {
    // appid: fetchConfig.headers.appid
  }

  options.initialCache = options.initialCache ?? false
  options.lazy = options.lazy ?? false
  options.onRequest = () => {
    // 处理请求逻辑
  }
  options.onResponse = () => {
    // 处理响应逻辑
  }

  //login get tocken
  const token = useCookie('token')
  if(token.value){
    options.headers.token = token.value
  }

  return options
}

export async function useHttp(key, url, options = {}) {
  options = useGetFetchOptions(options)
  options.key = key
  // 请求配置$，执行
  if(options.$){
    const data = ref(null)
    const error = ref(null)
    return await $fetch(url, options)
      .then((res) => {
        data.value = res.data
        return {
          data,
          error
        }
      })
      .catch((err) => {
        const msg = err?.data?.data
        if(process.client){
          // const { message } = 
          console.log("请求错误",msg)
        }
        error.value = msg
        return {
          data,
          error
        }
      })
  }

  let res = await useFetch(url,{
    ...options,
    // 响应拦截
    transform: (res) => {

      // return res
      
      if(res.code === 903){
          ElMessage.success(res.message);
          console.log("res",res.code)
          const user = useUser();
          user.value = null;
          const token = useCookie("token");
          token.value = null;
          // if (route.path != "/") {
          //   navigateTo("/", { replace: true });
          // }
          // ElMessage.success("token失效，请重新登录");
      }else{
        return res
      }
    }
  })

  // 客户端错误处理
  if(process.client && res.error.value) {
    const msg = res.error.value?.data?.data
    if(!options.lazy){
      console.log("服务端错误",msg)
    }
  }

  return res
}

// Get请求
export function useHttpGet(key, url, options = {}){
  options.method = 'GET'
  return useHttp(key, url, options)
}

// POST请求
export function useHttpPost(key, url, options = {}) {
  options.method = 'POST'
  return useHttp(key, url, options)
}

// DELETE请求
export function useHttpDelete(key, url, options = {}) {
  options.method = 'DELETE'
  return useHttp(key, url, options)
}



